/*
		ServEngine framework library
		A library to fast develop JEE online applications
	
		Copyright 2008 José Ignacio de Córdoba Álvaro

		Licensed under the Apache License, Version 2.0 (the "License");
		you may not use this file except in compliance with the License.
		You may obtain a copy of the License at

				http://www.apache.org/licenses/LICENSE-2.0

		Unless required by applicable law or agreed to in writing, software
		distributed under the License is distributed on an "AS IS" BASIS,
		WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
		See the License for the specific language governing permissions and
		limitations under the License.
	
		Jose Ignacio de Cordoba Alvaro
		http://ignacio.decordoba.com
*/

package com.servengine.portal;

import com.servengine.image.ThumbnailUtils;
import com.servengine.struts.AdminServiceAction;
import com.servengine.user.UserSessionSBean;

import com.servengine.util.ServletContextUtils;

import java.awt.Dimension;
import java.awt.Image;
import java.awt.image.BufferedImage;

import java.io.File;
import java.io.IOException;

import java.util.HashMap;
import java.util.Map;

import java.util.TreeSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * This class encloses all admin actions related to portal package
 */
public class AdminActions extends com.servengine.struts.ClientAction implements AdminServiceAction
{
	private static org.apache.commons.logging.Log log=org.apache.commons.logging.LogFactory.getLog(AdminActions.class.getName());
	//	Map<Integer, Category> categories;

	public void initAction(javax.naming.Context context)
	{
		/*	  try
		{
		  categories = new HashMap<Integer,Category>();
			for (Category category: portalmanager.getAllCategories())
				categories.put(category.getPkey(),category);
		} catch (Exception e)
		{
			throw new IllegalStateException();
		}
		log.info(getClass().getName() + " initialized");*/
	}

	public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			UserSessionSBean userSession=getUserSession(request);
			com.servengine.portal.PreferencesActionForm preferencesForm=(com.servengine.portal.PreferencesActionForm)form;
		  preferencesForm.setHomeurl(userSession.getPortal().getHomeurl());
			preferencesForm.setEmail(userSession.getPortal().getProperty(Portal.EMAIL_PROPERTY_NAME));
			preferencesForm.setLocale(userSession.getPortal().getLocale());
			return mapping.findForward("success");
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request, getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}

	/*	protected Collection<Category> getOtherCategories(Portal portal) throws RemoteException,FinderException
	{
		TreeSet<Category> treeSet = new TreeSet<Category>();
		Collection portalcategories = portal.getCategories();
		for (Category category: categories.values())
			if (!portalcategories.contains(category))
				treeSet.add(category);
		List<Category> othercategories = new ArrayList<Category>();
		othercategories.addAll(treeSet);
		return othercategories;
	}*/

	protected Map<String, String> getPortalWarnings(Portal portal)
	{
		Map<String, String> warnings=new HashMap<String, String>();
		/*    if (!portal.isHasguestuser())
			warnings.put("warning.noguestuser","user");*/
		if (portal.getHomeurl()==null||portal.getHomeurl().length()<5)
			warnings.put("warning.nohomeurl", "system");
		//		if (portal.getBgcolor()==null || portal.getTextcolor()==null || portal.getHtextcolor()==null || portal.getImgsurl()==null)
		//			warnings.put("warning.noportalcolors","system/graphics.jsp");
		/*Iterator it = getComponents().iterator();
		while (it.hasNext())
		{
			ComponentSBean component = (ComponentSBean)it.next();
			if (component.isSeemstoneedadminaccess())
				warnings.put("warning.adminclientseemstoneedadminrole","system/components.jsp");
		}
		if (statelessutils.getPortalNewuserroles(getPortalid()).size()==0)
			warnings.put("warning.nonewuserroles","user");*/
		return warnings;
	}

	public ActionForward store(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			UserSessionSBean userSession=getUserSession(request);
			PreferencesActionForm preferencesForm=(PreferencesActionForm)form;
			Portal portal=portalmanager.getPortal(userSession.getPortalid());
			portal.setHomeurl(preferencesForm.getHomeurl());
			portal.setDescription(preferencesForm.getDescription());
			portal.setLocale(preferencesForm.getLocale());
			portal.setProperty(Portal.EMAIL_PROPERTY_NAME, preferencesForm.getEmail());
			portalmanager.persist(portal);
			logManager.log(userSession.getPortalid(), userSession.getUser().getId(), "portal", "AdminActions", "store", null, request.getRemoteAddr());
			userSession.refresh(portal);
			setLocale(request, userSession.getLocale());
			return unspecified(mapping, form, request, response);
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request, getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}

	public ActionForward actions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			UserSessionSBean userSession=getUserSession(request);
			TreeSet actions=new TreeSet<Component>(userSession.getPortal().getActions());
			request.setAttribute("actions", actions);
			return mapping.findForward("actions");
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request, getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}

	public ActionForward actionsByRoleId(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			UserSessionSBean userSession=getUserSession(request);
			request.setAttribute("actions", portalmanager.getActionsByRoleId(userSession.getPortalid(), new Integer(request.getParameter("roleId"))));
			return mapping.findForward("actions");
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request, getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}

	public ActionForward graphics(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			UserSessionSBean userSession=getUserSession(request);
			PreferencesActionForm preferencesForm=(PreferencesActionForm)form;
			BeanUtils.copyProperties(preferencesForm, userSession.getPortal());
			preferencesForm.setEmail(userSession.getPortal().getProperty(Portal.EMAIL_PROPERTY_NAME));
			preferencesForm.setCssURL(userSession.getPortal().getProperty(ServletContextUtils.PORTAL_CSSURL_PROPERTY_NAME));
			//Pasado a tuportal:
			//			preferencesForm.setColors(userSession.getPortal().getProperty(ServletContextUtils.PORTAL_COLORS_PROPERTY_NAME));
			//			request.setAttribute("colorSchemeNames",((ServletContextUtils)getServletContextUtils()).getColorSchemeNames());
			preferencesForm.setHasLogo(new File(getServicedir(userSession.getPortalid(), "portal", true), "logo.jpg").exists());
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request, getErrorsFromException(e));
			return mapping.findForward("error");
		}
		return mapping.findForward("graphics");
	}

	public ActionForward storeGraphics(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			UserSessionSBean userSession=getUserSession(request);
			Portal portal=userSession.getPortal();
			PreferencesActionForm preferencesForm=(PreferencesActionForm)form;

			//Pasado a tuportal:
			/*			String colors = preferencesForm.getColorSchemeName()==null ?
				preferencesForm.getTextcolor()+","+preferencesForm.getHtextcolor()+","+preferencesForm.getBgcolor()+","+preferencesForm.getPbgcolor()+","+
				preferencesForm.getTextcolor2()+","+preferencesForm.getHtextcolor2()+","+preferencesForm.getBgcolor2()+","+preferencesForm.getPbgcolor2()
			: ((ServletContextUtils)getServletContextUtils()).getColorSchemes().getString(preferencesForm.getColorSchemeName());
			portalmanager.setProperty(portal.getId(),ServletContextUtils.PORTAL_COLORS_PROPERTY_NAME,colors);
*/
			//if (((com.tuportal.user.UserSessionSBean)userSession).isPremium())
			portalmanager.setProperty(portal.getId(), ServletContextUtils.PORTAL_CSSURL_PROPERTY_NAME, (preferencesForm.getCssURL()));
			if (preferencesForm.getLogo()!=null&&preferencesForm.getLogo().getFileSize()>0)
			{
				Image picture=ThumbnailUtils.JPEGtoImage(preferencesForm.getLogo().getInputStream());
				if (picture.getWidth(null)>120||picture.getHeight(null)>76) //TODO poner esto como parámetro de aplicación
				{
					BufferedImage bufferedImage=ThumbnailUtils.getScaledimage(picture, new Dimension(120, 76));
					ThumbnailUtils.writeJPG(bufferedImage, new java.io.File(getServicedir(portal.getId(), "portal", true), "logo.jpg"), (float)0.7);
				} else
					new com.servengine.util.File(getServicedir(portal.getId(), "portal", true), "logo.jpg").store(preferencesForm.getLogo().getInputStream());
			}
			getUserSession(request).refresh(portalmanager.getPortal(userSession.getPortalid()));
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request, getErrorsFromException(e));
			return mapping.findForward("error");
		}
		return graphics(mapping, form, request, response);
	}


}
